var express = require('express');
var router = express.Router();
let myQuery = require('../tools/db')
let {apiUrl,md5Suo,jwtSuo} = require('../tools/config');
let {jwtSign} = require('../tools/token');
let md5 = require('md5');
let {v4:uuid} = require('uuid');    


router.post('/login',async (req,res,next)=>{
    let {username,password} = req.body;
   
    
    if(!username || !password){
        next({code:400,msg:'用户名或密码不能为空'});
        return;
    }
    password = md5(password + md5Suo);
    let sql = `select * FROM e_member where username='${username}' AND password='${password}'`;
    let [err,result] = await myQuery(sql);

    
    if(err){
        next({code:500,msg:err});
        return;
    }
    if(result.length > 0){
       
        let data = {
            mid:result[0].mid,
            username:result[0].username
        }
        let token = jwtSign(data,jwtSuo,7 * 24 * 3600);

        res.send({code:200,msg:'ok',result:{token}});
    }else{
        next({code:400,msg:'用户名或密码错误'});
    }

    
})


router.post('/register', async (req,res,next)=>{
    let {username,password} = req.body;
 

    if(!username || !password){
        next({code:400,msg:'用户名或密码不能为空'});
        return;
    }
 
    let sql = `SELECT * FROM e_member WHERE username='${username}';`;
    let [err,result] = await myQuery(sql);
   
    if(err){
        next({code:500,msg:err});
        return;
    }
    if(result.length > 0){
        next({code:400, msg:'用户名已注册'});
        return;
    }
    //创建mid   密码加密    注册时间戳
    let mid = uuid();
    password = md5(password + md5Suo);

    
    let time = Date.now();
    
    let sql1 = `INSERT INTO e_member (mid, username, password, createdate) VALUES ('${mid}','${username}','${password}','${time}');`;

    let [err1,result1] = await myQuery(sql1);
    if(err1){
        next({code:500,msg:err1});
        return;
    }

    if(result1.insertId > 0){
        res.send({code:200,msg:'注册成功'});
    }else{
        next({code:500,msg:'注册失败，请稍后再试'});
        return;
    }

})

module.exports = router;